<template>
  <div class="container">
    <div class="left-board">
      <div class="logo-wrapper loginFormDes" style="height: 42px;">
        <div class="logo">组件库</div>
      </div>
      <el-scrollbar class="left-scrollbar">
        <!-- 左边：表单项 -->
        <div class="components-list">
          <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
            <div class="components-title">
              <i class="el-icon-menu" style="marginRight: 5px"></i>
              <!-- <svg-icon icon-class="component" /> -->
              {{ item.title }}
            </div>
            <draggable
              class="components-draggable"
              :list="item.list"
              :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
              :clone="cloneComponent"
              draggable=".components-item"
              :sort="false"
              @end="onEnd"
            >
              <div
                v-for="(element, index) in item.list"
                :key="index"
                class="components-item"
                @click="addComponent(element)"
              >
                <div class="components-body">
                  <svg-icon :icon-class="element.__config__.tagIcon" />
                  {{ element.__config__.label }}
                </div>
              </div>
            </draggable>
          </div>

          <!-- 左边：动态表单 -->
          <!-- <el-form ref="form" :model="form" :rules="rules" label-width="55px" :disabled="isEdit">
            <el-form-item label="表单名" prop="tableName">
              <el-input v-model="form.tableName" placeholder="请输入表单名" />
            </el-form-item>
            <el-form-item label="开启状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                          :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="tableRemark">
              <el-input type="textarea" v-model="form.tableRemark" placeholder="请输入备注" />
            </el-form-item>
          </el-form> -->
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board">
      <div class="action-bar">
        <!-- <el-button icon="el-icon-check" type="text" @click="save">保存</el-button> -->
               <!-- <el-button icon="el-icon-video-play" type="text" @click="run">
         运行
       </el-button> -->
        <el-button icon="el-icon-upload2" @click="showExcelDialog = true" type="text">
          Excel导入
        </el-button>
        <el-button icon="el-icon-view"  @click="showJson" type="text">
          查看json
        </el-button>
        <el-button icon="el-icon-view"  @click="preview" type="text"  >
          预览
        </el-button>
<!--        <el-button icon="el-icon-download" type="text" @click="download">-->
<!--          导出vue文件-->
<!--        </el-button>-->
<!--        <el-button class="copy-btn-main" icon="el-icon-document-copy" type="text" @click="copy">-->
<!--          复制代码-->
<!--        </el-button>-->
        <el-button class="delete-btn" icon="el-icon-delete" type="text" @click="empty">
          清空
        </el-button>
      </div>

      <!-- 中间，表单项 -->
      <el-scrollbar class="center-scrollbar">
        <el-row class="center-board-row" :gutter="formConf.gutter">
          <el-form
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'"

          >
            <draggable class="drawing-board" :list="drawingList" :animation="340" group="componentsGroup">
              <draggable-item
                v-for="(item, index) in drawingList"
                :key="item.renderKey"
                :drawing-list="drawingList"
                :current-item="item"
                :index="index"
                :active-id="activeId"
                :form-conf="formConf"
                @activeItem="activeFormItem"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
                @jumpStep="jumpStep"
              />
            </draggable>
            <div v-show="!drawingList.length" class="empty-info">
              <img src="@/assets/images/emptyform.png" alt="">
              <div class="info-title">从左侧拖入或点选组件进行表单设计</div>
            </div>
          </el-form>
        </el-row>
      </el-scrollbar>
    </div>

    <!-- 右边：组件属性/表单属性 -->
    <right-panel
      :active-data="activeData"
      :form-conf="formConf"
      :show-field="!!drawingList.length"
      :drawingList="drawingList"
      :newFormName="curFormName"
      :fields="drawingList"
      @tag-change="tagChange"
      @fetch-data="fetchData"
      @transTab="addtabs"
      @transStep="addSteps"
      @transCollapse="addCollapse"
      @changeFormConf="changeFormConf"
    />

   <!-- <form-drawer
     :visible.sync="drawerVisible"
     :form-data="formData"
     size="100%"
     :generate-conf="generateConf"
   /> -->
    
    <!-- 显示json -->
    <json-drawer
      size="60%"
      :visible.sync="jsonDrawerVisible"
      :json-str="JSON.stringify(formData)"
      @refresh="refreshJson"
    />

   <!-- <code-type-dialog
     :visible.sync="dialogVisible"
     title="选择生成类型"
     :show-file-name="showFileName"
     @confirm="generate"
   /> -->

 <!-- 表单预览 -->
 <el-dialog :modal-append-to-body="false" title="表单预览" :visible.sync="dialogPreviewVisible" :fullscreen="fullScreen" @close="dialogClose"  width="1000px">
    <span slot="title" class="el-dialog__title">
      表单预览
      <i class="el-icon-full-screen" v-if="!fullScreen" @click="()=>{fullScreen = true}" style="float:right;marginRight:25px;margin-top: 5px;"></i>
      <i class="el-icon-aim" v-else @click="()=>{fullScreen = false}" style="float:right;marginRight:35px;margin-top: 3px;"></i>
    </span>
    <el-tabs v-model="activeTab" id="previewBox">
    <el-tab-pane label="PC端" name="pc">
      <div v-if="this.showStepBtn" style="height: 32px;">
        <span style="float:right;" v-if="showStepBtn">
            <el-button icon="el-icon-arrow-left" @click="jumpStepBtn('down')" size="small">{{up}}</el-button>
            <el-button v-if="!showSumbit" @click="jumpStepBtn('up')" size="small">{{down}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
            <el-button v-if="showSumbit" size="small" type="primary"  @click="sumbitSeps()">{{sumbitBtn}}</el-button>
            <el-button @click="dialogClose()" size="small">{{finish}}</el-button>
        </span>
      </div>
      <parser :form-conf="formConfData" status="add" :originData="{}" v-if="dialogPreviewVisible" ref="parserRef"
        @cancel="dialogClose" :style="{width:fullScreen?'80%':'100%'}"  @change="changeSumbit"
        @click='drawerClick' :showHideData='showHideData' :key="time" @reset="reset"/>
    </el-tab-pane>
    <!-- <el-tab-pane label="移动端" name="mobile">
    <mobileparser :mobile-conf="formConfData" @cancel="dialogClose" @reset="reset" v-if="dialogPreviewVisible"></mobileparser>
    </el-tab-pane> -->
  </el-tabs>
 </el-dialog>
 <!-- Excel导入弹框 -->
 <div v-if="showExcelDialog"><ExcelImportDialog @closeExcelDialog="closeExcelDialog"></ExcelImportDialog></div>
<!--    <input id="copyNode" type="hidden">-->
     <el-drawer :visible.sync="drawer" direction="rtl" :before-close='closeDrawer'>
      <span slot="title" style="fontSize:18px;font-weight:500;color: #262626;">列显隐</span>
      <el-table :data="showHideData" size="small" border style="width:80%;marginLeft:10%;">
        <el-table-column prop="columnName" label="列名" align="center">
        </el-table-column>
        <el-table-column prop="hide" label="隐藏" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.hide"></el-checkbox>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { debounce } from 'throttle-debounce'
import { saveAs } from 'file-saver'
import ClipboardJS from 'clipboard'
import render from '@/components/render/render'
import FormDrawer from '@/views/infra/build/FormDrawer'
import JsonDrawer from '@/views/infra/build/JsonDrawer'
import RightPanel from './RightPanel'
import parser from './parser'
import SubFormEditDialog from './SubFormEditDialog.vue'
import ExcelImportDialog from './ExcelImportDialog.vue'
import {
  inputComponents, selectComponents, layoutComponents, formConf,organizationComponents
} from '@/components/generator/config'
import {
  exportDefault, beautifierConf, isNumberStr, titleCase, deepClone, isObjectObject
} from '@/utils/index'
import {
  makeUpHtml, vueTemplate, vueScript, cssStyle
} from '@/components/generator/html'
import { makeUpJs } from '@/components/generator/js'
import { makeUpCss } from '@/components/generator/css'
import drawingDefalut from '@/components/generator/drawingDefalut'
import logo from '@/assets/logo/logo.png'
import CodeTypeDialog from '@/views/infra/build/CodeTypeDialog'
import DraggableItem from './DraggableItem'
import {
  getDrawingList, saveDrawingList, getIdGlobal, saveIdGlobal, getFormConf
} from '@/utils/db'
import loadBeautifier from '@/utils/loadBeautifier'
import {CommonStatusEnum} from "@/utils/constants";
import {createForm, getForm, updateForm} from "@/api/bpm/form";
import {decodeFields} from "@/utils/formGenerator";
import mobileparser from '../../../mobileCustom/components/mobilePage'
import { makeRandom } from '@/utils/index'
import {delFormInfoEdit} from '@/api/custom/formDesigner'
let beautifier
const emptyActiveData = { style: {}, autosize: {} }
let oldActiveId
let tempActiveData
const drawingListInDB = getDrawingList()
const formConfInDB = getFormConf()
const idGlobal = getIdGlobal()

export default {
  components: {
    draggable,
    render,
    FormDrawer,
    JsonDrawer,
    RightPanel,
    CodeTypeDialog,
    DraggableItem,
    parser,
    SubFormEditDialog,
    ExcelImportDialog,
    mobileparser
  },
  props: ['isEdit','idDefault', 'newFormName'],
  data() {
    return {
      showSumbit: false,
      delChildData: [],
      curFormName: '',
      time:new Date().getMilliseconds(),
      logo,
      idGlobal,
      formConf,
      inputComponents,
      selectComponents,
      layoutComponents,
      labelWidth: 100,
      // drawingList: drawingDefalut,
      drawingData: {}, // 生成后的表单数据
      activeId: drawingDefalut[0].__config__.formId,
      drawer:false,
      drawingList: [], // 表单项的数组
      delDrawing: [],  //清空数据备份
      // activeId: undefined,
      // activeData: {},
      dialogPreviewVisible: false,
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      jsonDrawerVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: drawingDefalut[0], // 右边编辑器激活的表单项
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal),
      leftComponents: [
        {
          title: '输入型组件',
          list: inputComponents
        },
        {
          title: '选择型组件',
          list: selectComponents
        },
        {
          title: '布局型组件',
          list: layoutComponents
        },
        {
          title: '组织机构组件',
          list: organizationComponents
        }
      ],
      formConfData: {},
      // 表单参数
      form: {
        tableName: '',
        tableRemark: '',
        status: CommonStatusEnum.ENABLE,
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: "表单名不能为空", trigger: "blur" }],
        tableName: [{ message:'以字母开头，不能有汉字',pattern:/^[a-zA-Z][^\u4e00-\u9fa5]+$/,trigger:'blur'}],
        status: [{ required: true, message: "开启状态不能为空", trigger: "blur" }],
      },
      fullScreen: false,
      showHideData:[],
      showExcelDialog: false,
      activeTab:'pc',
      curCurrentItem:null
    }
  },
  computed: {
    showStepBtn () {
        this.up = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.up
        this.down = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.down
        this.finish = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.finish
        this.sumbitBtn = this.formConfData?.fields?.filter((_) => _.__config__.tag === 'Steps')[0]?.__config__.sumbitBtn
        const index = this.formConfData?.fields?.findIndex(comp => {
            return comp.__config__.tag === 'Steps'
        })
        if (index !== -1) {
            return true
        }
        return false
      },
  },
  watch: {
    // eslint-disable-next-line func-names
    // 'activeData.__config__.label': function (val, oldVal) {   //有bug,已改为在RightPanel.vue中处理
    //   if (
    //     this.activeData.placeholder === undefined
    //     || !this.activeData.__config__.tag
    //     || oldActiveId !== this.activeId
    //   ) {
    //     return
    //   }
    //   this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
    // },
    newFormName: {
        handler(val) {
            this.curFormName = val
        },
    },
    activeId: {
      handler(val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler(val) {
        this.saveDrawingListDebounce(val)
        if (val.length === 0) this.idGlobal = 100
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        this.saveIdGlobalDebounce(val)
      },
      immediate: true
    },
    idDefault: {
      handler(val) {
        this.idGlobal = val
      },
      immediate: true
    },
    activeData:{
      handler(val) {
        this.curCurrentItem = deepClone(val);
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    // 【add by awesome】不读缓存
    // if (Array.isArray(drawingListInDB) && drawingListInDB.length > 0) {
    //   this.drawingList = drawingListInDB
    // } else {
    //   this.drawingList = drawingDefalut
    // }
    // this.activeFormItem(this.drawingList[0])
    // if (formConfInDB) {
    //   this.formConf = formConfInDB
    // }
    loadBeautifier(btf => {
      beautifier = btf
    })
    const clipboard = new ClipboardJS('#copyNode', {
      text: trigger => {
        const codeStr = this.generateCode()
        this.$notify({
          title: '成功',
          message: '代码已复制到剪切板，可粘贴。',
          type: 'success'
        })
        return codeStr
      }
    })
    clipboard.on('error', e => {
      this.$message.error('代码复制失败')
    })
  },
  created() {
    // 读取表单配置
    const formId = this.$route.query && this.$route.query.formId
    if (formId) {
      getForm(formId).then(response => {
        const data = response.data
        this.form = {
          id: data.id,
          name: data.name,
          status: data.status,
          remark: data.remark
        }
        this.formConf = JSON.parse(data.conf)
        this.drawingList = decodeFields(data.fields)
        // 设置激活的表单项
        this.activeData = this.drawingList[0]
        this.activeId = this.activeData.__config__.formId
        // 设置 idGlobal，避免重复
        this.idGlobal += this.drawingList.length
      });
    }
  },
  methods: {
    sumbitSeps() {
      this.$refs.parserRef.submitForm();
    },
    changeSumbit(val) {
      this.showSumbit = val
    },
    jumpStepBtn (flag) {
        this.$refs.parserRef.jumpBtnStep(flag);
    },
    changeFormConf (jsView, editorValue) {
        if (!this.formConf.formJs) {
            this.formConf.formJs = {
                onLoad: '',
                beforeSubmit: '',
                afterSubmit: ''
            }
        }
        if (!this.activeData.change) {
            this.activeData.change = ''
        }
        if (!this.activeData.blur) {
            this.activeData.blur = ''
        }
        if (jsView === 'onLoad') {
            this.$set(this.formConf.formJs, 'onLoad', editorValue)
        } else if (jsView === 'before') {
            this.$set(this.formConf.formJs, 'beforeSubmit', editorValue)
        } else if (jsView === 'after') {
            this.$set(this.formConf.formJs, 'afterSubmit', editorValue)
        } else if (jsView === 'change') {
            this.$set(this.activeData, 'change', editorValue)
        } else if (jsView === 'blur') {
            this.$set(this.activeData, 'blur', editorValue)
        }
    },
    jumpStep (formIndex, stepIdx) {
        this.drawingList[formIndex].__config__.active = stepIdx + 1
    },
    // 关闭excel导入弹框
    closeExcelDialog (data) {
        this.showExcelDialog = false
        if (!data) {
            return
        }
        data.forEach(comp => {
            const newComp = this.createIdAndKey(comp)
            const copyComp = deepClone(newComp)
            this.drawingList.push(copyComp)
        })
    },
    drawerClick(renderKey){
        if (this.showHideData.length === 0) {
            const idx = this.getIRagIndex(renderKey);
            const childrenList=this.formConfData.fields[idx].__config__.children[0].__config__.children
            const showNum=this.formConfData.fields[idx].__config__.showNum
            showNum ? this.showHideData.push({columnName:'序号', hide: false}):[]
            childrenList.forEach(item=>{
                this.showHideData.push({
                    renderKey: renderKey,
                    columnName: item.__config__.label,
                    hide: false
                })
            })
        }
        this.drawer=true
    },
    closeDrawer(done){
    //   this.showHideData=[]
      done()
    },
    getIRagIndex(renderKey){
      let IndexM;
      this.formConfData.fields.forEach((item,index)=>{
        if(item.__config__.tag==='Subform' && item.__config__.renderKey === renderKey){
            IndexM=index
        }
      })
      return IndexM
    },
    updatePosition(e,originalEvent){
      if(e.draggedContext.element.__config__.tag==='Steps'){
        return false
      }else{
        if(e.draggedContext.futureIndex===0){
          return false
        }
      }
    },
    setObjectValueReduce(obj, strKeys, data) {
      const arr = strKeys.split('.')
      arr.reduce((pre, item, i) => {
        if (arr.length === i + 1) {
          pre[item] = data
        } else if (!isObjectObject(pre[item])) {
          pre[item] = {}
        }
        return pre[item]
      }, obj)
    },
    setRespData(component, resp) {
      const { dataPath, renderKey, dataConsumer } = component.__config__
      if (!dataPath || !dataConsumer) return
      const respData = dataPath.split('.').reduce((pre, item) => pre[item], resp)

      // 将请求回来的数据，赋值到指定属性。
      // 以el-tabel为例，根据Element文档，应该将数据赋值给el-tabel的data属性，所以dataConsumer的值应为'data';
      // 此时赋值代码可写成 component[dataConsumer] = respData；
      // 但为支持更深层级的赋值（如：dataConsumer的值为'options.data'）,使用setObjectValueReduce
      this.setObjectValueReduce(component, dataConsumer, respData)
      const i = this.drawingList.findIndex(item => item.__config__.renderKey === renderKey)
      if (i > -1) this.$set(this.drawingList, i, component)
    },
    fetchData(component) {
      const { dataType, method, url } = component.__config__
      if (dataType === 'dynamic' && method && url) {
        this.setLoading(component, true)
        this.$axios({
          method,
          url
        }).then(resp => {
          this.setLoading(component, false)
          this.setRespData(component, resp.data)
        })
      }
    },
    setLoading(component, val) {
      const { directives } = component
      if (Array.isArray(directives)) {
        const t = directives.find(d => d.name === 'loading')
        if (t) t.value = val
      }
    },
    //激活组件
    activeFormItem(currentItem) {
      this.activeData = currentItem
      if (this.activeData.__config__.tag === 'pictureSelect') {
        this.activeData.options.forEach(item => {
            if (!item.id) {
                item.id = makeRandom()
            }
        })
      }
      this.activeId = currentItem.__config__.formId
    },
    //把组件从左侧拖拽到中间后，激活组件
    onEnd(obj) {
      if (obj.from !== obj.to) {
        this.fetchData(tempActiveData)
        this.activeData = tempActiveData
        this.activeId = this.idGlobal
        this.$emit('updateFieldId',this.idGlobal)
      }
    },
    //添加组件
    addComponent(item) {
      if(item.__config__.tag==='Steps' && this.drawingList.some(item=>item.__config__.tag==='Steps')){
         this.$message({
          message: '表单内只允许一个步骤条',
          type: 'warning'
        });
        return
      }
      const clone = this.cloneComponent(item)
      this.fetchData(clone)
      if(item.__config__.tag==='Steps'){
        this.drawingList.unshift(clone)
      }else{
        this.drawingList.push(clone)
      }
      this.activeFormItem(clone)
      this.$emit('updateFieldId',this.idGlobal)
    },
    //克隆组件
    cloneComponent(origin) {
      const clone = deepClone(origin)
      const config = clone.__config__
      config.span = this.formConf.span // 生成代码时，会根据span做精简判断
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config.label)
      tempActiveData = clone
      return tempActiveData
    },
    createIdAndKey(item) {
      const config = item.__config__
      config.formId = ++this.idGlobal
      config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
      if (config.layout === 'colFormItem') {
        item.__vModel__ = `field${this.idGlobal}`
      } else if (config.layout === 'rowFormItem') {
        if (config.tag === 'Subform') {
            item.__vModel__ = this.makeTableName()
        }
        config.componentName = config.componentName || `row${this.idGlobal}`
        !Array.isArray(config.children) && (config.children = [])
        // delete config.label // rowFormItem无需配置label属性
      }
      if (Array.isArray(config.children)) {
        config.children = config.children.map(childItem => this.createIdAndKey(childItem))
      }
      if(config.tag==='Steps'){
        item.activeId=`field${this.idGlobal}`
        // item.__vModel__ = undefined
        // this.$store.commit('CHANGE_STEPS', {key:`field${this.idGlobal}`,value:0})
      }
      this.$emit('updateFieldId',this.idGlobal)
      return item
    },
    makeTableName () {
        let date = new Date(Date.now())
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        const tt = 'table' + year + month + day + hour + minute + second + this.getRandomStr(5)
        return tt
    },
    //生成随机数
    getRandomStr(len) {
        var str = "";
        for (let i = 0; i < len; i++) {
            str += Math.ceil(Math.random() * 10)
        }
        return str
    },
    // 获得表单配置数据,用于json显示
    AssembleFormData() {
      this.formData = {
        fields: deepClone(this.drawingList),
        ...this.formConf
      }
    },
    //显示表单预览弹窗
    preview(){
      this.showSumbit = false
      const stepsList = this.drawingList.filter((_) => _.__config__.tag === 'Steps')
      if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
        this.drawingList.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
      }
      this.formConfData = {
        fields: this.drawingList,
        ...this.formConf
      }
      this.fullScreen = false
      this.dialogPreviewVisible = true
    },
    save() {
      // this.AssembleFormData()
      // console.log(this.formData)
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        const form = {
          conf: JSON.stringify(this.formConf), // 表单配置
          fields: this.encodeFields(), // 表单项的数组
          ...this.form // 表单名等
        }
        // 修改的提交
        if (this.form.id != null) {
          updateForm(form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.close()
          });
          return;
        }
        // 添加的提交
        createForm(form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.close()
        });
      });
    },
    /** 关闭按钮 */
    close() {
      this.$tab.closeOpenPage({ path: "/bpm/manager/form" });
    },
    // 关闭弹框的回调
    dialogClose () {
      this.showSumbit = false
      const stepsList = this.drawingList.filter((_) => _.__config__.tag === 'Steps')
      if(stepsList?.length > 0){  //步骤条预览都是从步骤一开始
        this.drawingList.filter((_) => _.__config__.tag === 'Steps')[0].__config__.active = 1
      }
        this.dialogPreviewVisible = false
        this.formConfData.fields.forEach(comp => {
            if (comp.__config__.tag === "Subform" && !comp.__config__.valueConfig) { //子表单有默认值时 不清空数据
                comp.tableData = []
            }
        });
    },
    encodeFields() {
      const fields = []
      this.drawingList.forEach(item => {
        fields.push(JSON.stringify(item))
      })
      return fields
    },
    generate(data) {
      const func = this[`exec${titleCase(this.operationType)}`]
      this.generateConf = data
      func && func(data)
    },
    execRun(data) {
      this.AssembleFormData()
      this.drawerVisible = true
    },
    execDownload(data) {
      const codeStr = this.generateCode()
      const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
      saveAs(blob, data.fileName)
    },
    execCopy(data) {
      document.getElementById('copyNode').click()
    },
    //清空组件
    empty() {
      this.$confirm('确定要清空所有组件吗？', '提示', { type: 'warning' }).then(
        () => {
          this.delDrawing = JSON.parse(JSON.stringify(this.drawingList))  // 清空数据备份 
          this.drawingList = []
          this.idGlobal = 100
        }
      )
    },
    //复制组件
    drawingItemCopy(item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      list.push(clone)
      this.activeFormItem(clone)
    },
    //删除组件
    drawingItemDelete(index, list, subitem) {
      let delItem = list.splice(index, 1)
      let deleteFlag = 'main' // 删除数据标识（主表/子表单）
      let tableName = ''
      if(subitem && subitem.componentName === 'el-row'){
        deleteFlag = 'sub'
        this.drawingList.forEach(val=>{
          if(val.__config__.children){
            if(val.__config__.children[0].__config__.renderKey===subitem.__config__.renderKey){
              tableName = val.__vModel__;
            }
          }
        })
      }
      this.$emit('deleteItem', deleteFlag, delItem[0], tableName)
      if(this.isEdit && delItem[0].__config__.tag === 'Subform'){
        this.delChildData.push(delItem[0].__vModel__)
        const len = this.drawingList.length
          if (len) {
            this.activeFormItem(this.drawingList[len - 1])
          }
        this.$emit('deleteChildData',this.delChildData)

        // delFormInfoEdit(delItem[0].__vModel__).then(res=>{
        //   if(res.code===0){
        //     this.$nextTick(() => {
        //     const len = this.drawingList.length
        //     if (len) {
        //       this.activeFormItem(this.drawingList[len - 1])
        //     }
        //   })
        //   }
        // })
      }else{
        this.$nextTick(() => {
        const len = this.drawingList.length
        if (len) {
          this.activeFormItem(this.drawingList[len - 1])
        }
      })
      }
    },
    generateCode() {
      const { type } = this.generateConf
      this.AssembleFormData()
      const script = vueScript(makeUpJs(this.formData, type))
      const html = vueTemplate(makeUpHtml(this.formData, type))
      const css = cssStyle(makeUpCss(this.formData))
      return beautifier.html(html + script + css, beautifierConf.html)
    },
    //显示json
    showJson() {
      this.AssembleFormData()
      this.jsonDrawerVisible = true
    },
    download() {
      this.dialogVisible = true
      this.showFileName = true
      this.operationType = 'download'
    },
    run() {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'run'
    },
    copy() {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'copy'
    },
    tagChange(newTag) {
      newTag = this.cloneComponent(newTag)
      newTag.__vModel__ = this.curCurrentItem.__vModel__
      const config = newTag.__config__
      this.activeId = config.formId
      this.activeData.__config__.span = config.span
      this.activeData.__config__.tag = config.tag
      this.activeData.__config__.tagIcon = config.tagIcon
      this.activeData.__config__.document = config.document
      if (typeof this.activeData.__config__.defaultValue === typeof config.defaultValue) {
        this.activeData.__config__.defaultValue = config.defaultValue
      }
      Object.keys(newTag).forEach(key => {
        if (newTag[key] !== undefined) {
          this.activeData[key] = newTag[key];
        }
      })
      this.activeData = newTag
      this.activeData.__vModel__ = this.curCurrentItem.__vModel__
      this.activeData.__config__.label = this.curCurrentItem.__config__.label
      this.activeData.__config__.descriptionMessage = this.curCurrentItem.__config__.descriptionMessage
      this.activeData.isTagChange = true
      this.updateDrawingList(newTag, this.drawingList)
    },
    updateDrawingList(newTag, list) {
      const index = list.findIndex(item => item.__config__.formId === this.activeId)
      if (index > -1) {
        list.splice(index, 1, newTag)
      } else {
        list.forEach(item => {
          if (Array.isArray(item.__config__.children)){
            this.activeId = this.curCurrentItem.__config__.formId;
            newTag.__config__.formId = this.curCurrentItem.__config__.formId;
            this.updateDrawingList(newTag, item.__config__.children)
          }
        })
      }
    },
    refreshJson(data) {
        this.drawingList = []
        data.fields.forEach(comp => {
            const newComp = this.createIdAndKey(comp)
            const copyComp = deepClone(newComp)
            this.drawingList.push(copyComp)
        })
        delete data.fields
        this.formConf = data
    },
    /* 选项卡相关 */
    addtabs(tab) {
      const tabsComponent = layoutComponents.find(
        (item) => item.__config__.tag === "el-tabs"
      );
      const clone = this.cloneComponent(tabsComponent);
      let currentIndex;
      this.drawingList.forEach((item, index) => {
        if (item.__config__.tag === clone.__config__.tag) {
          currentIndex = index;
        }
        return currentIndex;
      });
      this.drawingItemDelete(currentIndex, this.drawingList);
      this.addComponent(tab);
    },
    /* 步骤条相关 */
    addSteps(step) {
      const stepsComponent = layoutComponents.find(
        (item) => item.__config__.tag === "Steps"
      );
      const clone = this.cloneComponent(stepsComponent);
      let currentIndex;
      this.drawingList.forEach((item, index) => {
        if (item.__config__.tag === clone.__config__.tag) {
          currentIndex = index;
        }
        return currentIndex;
      });
      this.drawingItemDelete(currentIndex, this.drawingList);
      this.addComponent(step);
    },
    /* 折叠面板相关 */
    addCollapse(collapse) {
      const collapseComponent = layoutComponents.find(
        (item) => item.__config__.tag === "el-collapse"
      );
      const clone = this.cloneComponent(collapseComponent);
      let currentIndex;
      this.drawingList.forEach((item, index) => {
        if (item.__config__.tag === clone.__config__.tag) {
          currentIndex = index;
        }
        return currentIndex;
      });
      this.drawingItemDelete(currentIndex, this.drawingList);
      this.addComponent(collapse);
    },
    //重置
    reset() {
      this.showSumbit = false
      this.time = new Date().getMilliseconds()
    },
  }
}
</script>

<style lang='scss'>
@import '@/styles/home';
#previewBox .el-tabs__nav-scroll{
  display:flex;
  justify-content: center;
}
.el-dialog__title{
    width: 100% !important;
}
.action-bar {
  .el-button + .el-button{
    margin-left: 10px;
  }
  .el-button--text{
    width: 85px;
    height: 36px;
    background: #edf6ff;
    background: #edf6ff;
    border-radius: 4px !important;
    color: #1890FF;
  }
  .el-button--medium{
    font-size: 12px;
  }
  .el-button--text:nth-child(3){
    width: 70px;
  }
  .el-button--text:nth-child(4){
    width: 70px;
    background: #ffe7e7;
  }
  i{
    font-size: 14px;
  }
}
.loginFormDes::after{
    content: "";
    position: absolute;
    right: -1px;
    bottom: 0;
    width: 1px;
    height: 52px;
    background-color: #f1e8e8;
    z-index: 1;
}
</style>
